package com.itheima.health.controller;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.aliyuncs.http.HttpResponse;
import com.itheima.health.constant.MessageConstant;
import com.itheima.health.constant.RedisMessageConstant;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.Member;
import com.itheima.health.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/login")
public class LoginController {

    //连接池
    @Autowired
    private JedisPool jedisPool;

    @Reference
    private MemberService memberService;

    /**
     * 手机快速登录
     * @param loginInfo
     * @param res
     * @return
     */
    @PostMapping("/check")
    public Result check(@RequestBody Map<String,String> loginInfo, HttpServletResponse res){

        //检验验证码

        //从连接池获取连接
        Jedis jedis = jedisPool.getResource();

        //获取手机号码，loginInfo包含了手机号和验证码
        String telephone = loginInfo.get("telephone");

        //拼接redis的key，为了业务规范
        String key = RedisMessageConstant.SENDTYPE_LOGIN + ":" + telephone;

        //再从redis中的jedis取出验证码
        String codeInRedis = jedis.get(key);

        //判断验证码是否有值
        if (StringUtils.isEmpty(codeInRedis)){

            //如果验证码为空，则提示请重新获取验证码
            return new Result(false,"请重新获取验证码");
        }
        //判断用户输入的验证码与生成的验证码是有一致
        if (!codeInRedis.equals(loginInfo.get("validateCode"))){

            //如果不一致，则提示验证码错误
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
        //如果一致，则删除验证码，防止内存垃圾过多
        jedis.del(key);

        jedis.close();

        //通过查询电话号码判断是否为会员
        Member member = memberService.findByTelephone(telephone);

        //如果不是会员，则添加会新会员
        if (null == member){

            //新建会员
             member = new Member();

            //设置信息
            member.setRemark("手机快速登录");
            member.setRegTime(new Date());
            member.setPhoneNumber(telephone);

            //调用业务层，添加会员
            memberService.add(member);
        }
        //并添加cookie跟踪
        Cookie cookie = new Cookie("login_member_telephone",telephone);

        //设置存活时间，30天
        cookie.setMaxAge(30*24*60*60);

        //路径
        cookie.setPath("/");

        //添加进cookie
        res.addCookie(cookie);

        //返回页面，登录成功
        return new Result(true, MessageConstant.LOGIN_SUCCESS);
    }
}
